package com.example.ribbonconsumer.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.example.ribbonconsumer.model.User;
import com.example.ribbonconsumer.service.UserService;
import com.netflix.hystrix.HystrixCollapser.Scope;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private RestTemplate restTemplate;

	@HystrixCollapser(batchMethod="findAll",collapserProperties={
			//设置批处理过程中每个命令延迟的时间，单位毫秒
			@HystrixProperty(name="timerDelayInMilliseconds",value="5000"),
			//设置一次请求合并批处理中允许的最大请求数
			@HystrixProperty(name="maxRequestsInBatch",value="20"),
			},scope=Scope.GLOBAL)
	@Override
	public User find(Long id) {
		//return restTemplate.getForObject("http://HELLO-SERVICE/users/{1}", User.class, id);
		return null;
	}

	@HystrixCommand(fallbackMethod="error")
	@Override
	public List<User> findAll(List<Long> ids) {
		System.out.println("合并请求");
		ParameterizedTypeReference<List<User>> responseType = new ParameterizedTypeReference<List<User>>() {};
		ResponseEntity<List<User>> user = restTemplate.exchange("http://HELLO-SERVICE/users?ids={1}", HttpMethod.GET,
				null, responseType, StringUtils.join(ids, ","));
		return user.getBody();
	}
	
	public List<User> error(List<Long> ids){
		return new ArrayList<>();
	}

}
